<?php
require_once(DATA_PATH."table_dao.php");
class Amazon{
    private $ch,$body;
    public function GetPrice($url){
        $Data_price_cache = array(
          "flag"	=>	md5($url),
          "price"	=>	"",
          );
        $price_cache_dao = new table_dao("price_cache");
        $data = $price_cache_dao->get($Data_price_cache);
        if($data==NULL){
          $curl = new curl($url);
          $this->body = $curl->execute();
          $Data_price_cache["price"] = $this->Regex();
          $price_cache_dao->add($Data_price_cache);
          $result = $Data_price_cache["price"];
        }else{
          $result = checknull("price", checknull("0", $data));
        }
        return $result;
    }
  
    public function GetPriceByItemid($itemid){
        $data = array(
            "site"=> "amazon",
            "type"=> "shopping",
            "itemid"=> $itemid,
            "op"  => "item",
        );
        $test = new logic($data);
        $apidata = $test->Output("item","ARRAY"); 
        $apidata_url = checknull("url", $apidata);
        return $this->GetPrice($apidata_url);
    }
    
    private function Regex(){
        $price = 0;
        //echo "check";
        $reg_amazon = array(
            '/<(b|span) class="priceLarge">(.[^\d]*)(.*)<\/(b|span)>/i',
            '/<(span) class="price">(.[^\d]*)(.[^<]*)<\/span>/i',
        );
        //$reg_mbok = "/エラー/";
        foreach($reg_amazon as $reg){
            //echo "\n".$reg_value."\n";
            if(preg_match( $reg, $this->body, $m )){
                if(isset($m[3])){
                    $temp = str_replace(array("￥",","," "),NULL,$m[3]);
                    if(is_numeric($temp)){
                      $price = intval( $temp );
                    }
                    if($price!=0){break;}
                }
            }
        }
        return $price;
    }
}
?>